import {onMounted, ref} from "vue"
import type { Query } from "@/interface/Query";
import type { House } from "@/interface/House";
import {auditApi, listApi, operatorApi, removeApi , unbindApi } from "@/controller/HouseApi";
import { residentOperateApi } from "@/controller/UserApi"
import type {TableColumnsType} from "ant-design-vue";
import {message} from "ant-design-vue";
import { useLoginStore } from "@/stores/loginStore"
import type {HouseUser} from "@/interface/HouseUser";
import type {User} from "@/interface/User";

export default function () {


    const loginStore = useLoginStore();

    onMounted(()=> {
        list();
    });

    let searchBox = ref<boolean>(true);

    let queryModel = ref({
        page : 1,
        size : 10,
        keyWord : ''
    } as Query);

    let data = ref([] as House[]);
    let total = ref(0);
    function list() {
        listApi(queryModel.value).then( res => {
            if(res.code == 200) {
                data.value = res.data.records;
                total.value = parseInt(res.data.totalRow);
            }
        });
    }


    let userColumns = ref<TableColumnsType>([
        {
            title: '姓名',
            fixed: 'left',
            dataIndex: 'realName',
            width: 110,
            align: 'center',
            resizable: true
        },
        {
            title: '身份证',
            dataIndex: 'idCard',
            width: 90,
            align: 'center',
            resizable: true
        },
        {
            title: '手机号',
            dataIndex: 'phoneNumber',
            width: 90,
            align: 'center',
            resizable: true
        },
        {
            title: '性别',
            dataIndex: 'sex',
            align: 'center',
            width: 90,
            resizable: true
        },
        {
            title: '类型',
            dataIndex: 'type',
            align: 'center',
            width: 90,
            resizable: true
        },
        {
            title: '认证状态',
            dataIndex: 'status',
            align: 'center',
            width: 90,
            resizable: true
        },
        {
            title: '操作',
            fixed: 'right',
            dataIndex: 'action',
            align: 'center',
            width: 80,
            resizable: true
        },
    ])
    let columns = ref<TableColumnsType>([
        {
            title: '楼栋号',
            fixed: 'left',
            dataIndex: 'floorName',
            width: 110,
            align: 'center',
            resizable: true
        },
        {
            title: '单元号',
            dataIndex: 'unitNumber',
            width: 90,
            align: 'center',
            resizable: true
        },
        {
            title: '房间号',
            dataIndex: 'building',
            width: 90,
            align: 'center',
            resizable: true
        },
        {
            title: '楼层',
            dataIndex: 'floor',
            width: 90,
            align: 'center',
            resizable: true
        },
        {
            title: '房间类型',
            dataIndex: 'roomType',
            width: 90,
            align: 'center',
            resizable: true
        },
        {
            title: '建筑面积',
            dataIndex: 'area',
            width: 90,
            align: 'center',
            resizable: true
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 90,
            align: 'center',
            resizable: true
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 130,
            align: 'center',
            resizable: true
        },
    ]);

    function handleResizeColumn(w : any, col : any) {
        col.width = w;
    }

    let auditStore = ref({
        open: false,
        houseUser: {} as HouseUser,
        remark: ''
    });

    function audit(data : HouseUser) {
        auditStore.value.open = true;
        auditStore.value.houseUser.userId = data.userId;
        auditStore.value.houseUser.houseId = data.houseId;
    }


    function pageChange(page : number,size : number) {
        queryModel.value.page = page;
        queryModel.value.size = size;
        list();
    }

    function resetQuery() {
        queryModel.value = {
            page : 1,
            size : 10,
            keyWord : ''
        } as Query
        list();
    }

    let operatorStore = ref({
        open: false,
        cmd: 0,
        house: {} as House
    });
    let formRef = ref();
    let rules = {
        floorName: [{ required: true, message: '请输入楼栋号', trigger: 'blur' }],
        unitNumber: [{ required: true, message: '请输入单元号', trigger: 'blur' }],
        building: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
        floor: [{ required: true, message: '请输入楼层', trigger: 'blur' }],
        roomType: [{ required: true, message: '请输入房间类型', trigger: 'blur' }],
        area: [{ required: true, message: '请输入建筑面积', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
    }

    let auditFormRef = ref();

    let auditRules = {
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
    }

    function auditOk() {
        auditFormRef.value.validate().then(() => {
            auditApi(auditStore.value.houseUser).then( res => {
                if(res.code == 200) {
                    list();
                    auditCancel();
                    message.success( "审核成功")
                }else {
                    message.error(res.msg);
                }
            });
        }).catch(( err : any) => {console.log(err)})
    }

    function auditCancel() {
        auditStore.value.open = false;
        auditStore.value.houseUser = {} as HouseUser;
    }
    function submit() {
        formRef.value.validate().then(() => {
            operatorApi(operatorStore.value.house).then( res => {
                if(res.code == 200) {
                    list();
                    cancel();
                    message.success( operatorStore.value.cmd == 0 ? "添加成功" : "编辑成功")
                }else {
                    message.error(res.msg);
                }
            });
        });
    }
    function operator(cmd : number,data ? : House) {
        operatorStore.value.cmd = cmd;
        operatorStore.value.open = true;
        if(cmd == 1 && data) {
            operatorStore.value.house = data;
        }else {
            if(loginStore.loginInfo.user.user.properties) {
                operatorStore.value.house.propertyId =  loginStore.loginInfo.user.user.properties.id;
            }
        }
    }

    function cancel() {
        operatorStore.value.open = false;
        operatorStore.value.house = {} as House;
    }

    function remove(ids : string[]) {
        removeApi(ids).then( res => {
            if(res.code == 200) {
                message.success("删除成功");
                list();
            }else {
                message.error(res.msg);
            }
        });
    }

    let residentStore = ref({
       open : false,
       user : {} as User,
       houseId: '',
       cmd : 0
    });

    let residentRules = {
        name : [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone : [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        idCard : [{ required: true, message: '请输入身份证号', trigger: 'blur' }]
    }

    function residentOperator(cmd : number, houseId : string | null , data ? : User) {
        residentStore.value.cmd = cmd;
        residentStore.value.open = true;
        if(houseId) {
            residentStore.value.houseId = houseId;
        }
        if(data) {
            residentStore.value.user = data;
        }
    }

    let residentFrom = ref();
    let residentTypes = [{
        label : "业主",
        value : 2
    },
    {
        label : "住户",
        value : 3
    },
    {
        label : "租户",
        value : 4
    }]

    function residentCancel() {
        residentStore.value.open = false;
        residentStore.value.user = {
        } as User;
        residentStore.value.houseId = '';
        residentFrom.value.resetFields();
    }

    function residentOk() {
        residentFrom.value.validate().then(() => {
            if(loginStore.loginInfo.user.user.properties) {
                residentStore.value.user.propertyId =  loginStore.loginInfo.user.user.properties.id as any;
            }
            residentOperateApi(residentStore.value.user,residentStore.value.houseId).then( res => {
                if(res.code == 200) {
                    residentCancel();
                    list();
                    message.success(residentStore.value.cmd == 0 ? "添加成功" : '编辑成功');
                }else {
                    message.error(res.msg);
                }
            });
        }).catch( (res : any) => {
            console.log(res);
        })
    }

    function unbind( data : HouseUser ) {
        unbindApi(data).then( res => {
            if(res.code == 200) {
                list();
                message.success("解绑成功");
            }else {
                message.error(res.msg);
            }
        });
    }

    return {
        searchBox , resetQuery , list , queryModel , data , total ,
        handleResizeColumn , columns , pageChange , operatorStore ,
        operator , formRef , submit , rules , cancel , userColumns ,
        remove , auditStore , audit , auditOk , auditRules , auditFormRef ,
        auditCancel , residentFrom , residentStore , residentRules , residentOperator ,
        residentTypes , residentOk , residentCancel , unbind
    }
}
